package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.CarFleetDao;
import com.hhs.storage.service.BaseRoleService;
import com.hhs.storage.service.BaseUserService;
import com.hhs.storage.service.CarFleetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.CarService;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2022-12-20
 */
@Service
@Transactional
public class CarFleetServiceImpl extends ServiceImpl<CarFleetDao, CarFleet> implements CarFleetService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private BaseRoleService roleService;
    @Autowired
    private BaseUserService userService;
    @Resource
    private CarService carService;
    @Override
    public Map<String, Object> getAll(CarFleet carFleet, InputParam inputParam) {
        //设置模糊查询的通配符
        if (org.apache.commons.lang.StringUtils.isNotEmpty(carFleet.getName())){
            carFleet.setName("%"+carFleet.getName()+"%");
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(inputParam.getPrincipalName())){
            inputParam.setPrincipalName("%"+inputParam.getPrincipalName()+"%");
        }
        //如果用户只是车队长，只能查询自身相关数据
        boolean isCDZ=roleService.hasOnlyRole(SysUtil.ROLE_FLAG_CDZ,SysUtil.getLoginUserId(request));
        if (isCDZ){//如果是车队长，查询条件只能查询与自己相关的车队数据
            carFleet.setPrincipalId(SysUtil.getLoginUserId(request));
        }
        List<CarFleet> list=this.baseMapper.query(carFleet,inputParam);
        //统计有多少正常车辆和非正常车辆
        for (int i = 0; i < list.size(); i++) {
            CarFleet temp=list.get(i);
            QueryWrapper<Car> carQueryWrapper=new QueryWrapper<>();
            carQueryWrapper.eq("car_fleet_id",temp.getId());
            List<Car> carList=carService.list(carQueryWrapper);
            int free=0;
            int error=0;
            int work=0;
            for (int j = 0; j <carList.size() ; j++) {
                Car car=carList.get(j);
                if (car.getState()==Car.STATE_FREE){
                    free++;
                }
                if (car.getState()==Car.STATE_WORK){
                    work++;
                }
                if (car.getState()==Car.STATE_ERROR){
                    error++;
                }
            }
            Map<String,Integer> countMap =new HashMap<>();
            countMap.put("free",free);
            countMap.put("work",work);
            countMap.put("error",error);
            countMap.put("total",error+free+work);
            temp.setCountMap(countMap);
        }
        //查询
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", list);
        map.put("total", this.baseMapper.total(carFleet,inputParam));
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> addOrUpdate(CarFleet carFleet) {
        //新增
        if (StringUtils.isEmpty(carFleet.getId())) {
            //如果用户只是车队长，新增强制指定车队负责人为自己
            boolean isCDZ=roleService.hasOnlyRole(SysUtil.ROLE_FLAG_CDZ,SysUtil.getLoginUserId(request));
            if (isCDZ){//如果是车队长，新增强制指定车队负责人为自己
                carFleet.setPrincipalId(SysUtil.getLoginUserId(request));
            }
            if(StringUtils.isEmpty(carFleet.getName())||StringUtils.isEmpty(carFleet.getPrincipalId())
//                    || carFleet.getType()==null  //取消车队类型数据验证
                    || StringUtils.isEmpty(carFleet.getPhone())
                    || StringUtils.isEmpty(carFleet.getBank())
                    || StringUtils.isEmpty(carFleet.getIdCard())){
                return ResponseInfo.error("参数错误");
            }
            //设置车队类型与车队负责人一致
            BaseUser user=userService.getById(carFleet.getPrincipalId());
            carFleet.setType(user.getCarFleetType());
            //设置当前时间
            carFleet.setCreateTime(LocalDateTime.now());
            carFleet.setId(SysUtil.UUID());

            this.save(carFleet);
        } else {//修改
            if(StringUtils.isEmpty(carFleet.getName()) ||StringUtils.isEmpty(carFleet.getPrincipalId())||
                    carFleet.getType()==null|| StringUtils.isEmpty(carFleet.getPhone())
                    || StringUtils.isEmpty(carFleet.getBank())
                    || StringUtils.isEmpty(carFleet.getIdCard())){
                return ResponseInfo.error("参数错误");
            }
            this.updateById(carFleet);
        }
        return ResponseInfo.success(null);
    }

    @Override
    public Map<String, Object> dele(String id) {
        this.removeById(id);
        return ResponseInfo.success(null);
    }

    @Override
    public Map<String, Object> listAll(InputParam inputParam) {
        QueryWrapper<CarFleet> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        List<CarFleet> list = this.list(queryWrapper);
        return ResponseInfo.success(list);
    }
}
